<template>
  <div>
    <h2>{{ name }} - {{ age }}</h2>
    <button @click="changeName">修改name</button>
    <button @click="changeAge">修改age</button>
  </div>
</template>

<script>
import { ref, watchEffect } from "vue";

export default {
  setup(props) {
    const name = ref("why");
    const age = ref(18);

    const stop = watchEffect((onInvalidate) => {
      const timer = setTimeout(() => {
        console.log("网络请求成功");
      }, 2000);

      onInvalidate(() => {
        // 清除副作用
        clearTimeout(timer);
        console.log("onInvalidate");
      });
      console.log("name: " + name.value, "age: " + age.value);
    });

    const changeName = () => (name.value = "kobe");
    const changeAge = () => {
      age.value++;
      if (age.value > 25) {
        stop();
      }
    };

    return { name, age, changeName, changeAge };
  },
};
</script>

<style scoped></style>
